package org.ztest.guava;

import java.util.concurrent.Executors;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.Subscribe;

// 测试Guava异步EventBus
public class TestAsyncEventBus
{
    // 事件对象(自定义)
    static class TestEventObject
    {
        private String name;

        public TestEventObject(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return "TestEventObject[name=" + name + "]";
        }
    }

    // 标注订阅方法，该方法必须有且只有一个参数
    // 当对应类型的事件被触发时，该方法将被执行
    @Subscribe
    public void onSubscribe(TestEventObject event) {
        System.out.println("Receive event:" + event + ", Thread:" + Thread.currentThread());
    }

    public void test() {
        System.out.println("Current thread:" + Thread.currentThread());
        // AsyncEventBus所有事件均在构造函数指定的线程池中执行
        AsyncEventBus bus = new AsyncEventBus(Executors.newSingleThreadExecutor());
        bus.register(new TestAsyncEventBus());
        bus.post(new TestEventObject("TestEventObject"));
    }
}
